package com.wuqi.dev.ipcdemo;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.IntDef;
import android.support.annotation.Nullable;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by Risky57 on 2017/5/9.
 */

public class RemoteService extends Service {
    @Nullable
    @Override
    public IBinder onBind (Intent intent) {
        return null;
    }

    @Override
    public void onCreate () {
        super.onCreate();
        Log.d("RemoteService", "单独进程的服务已开启");
        initSocketServer();
    }

    private void initSocketServer () {
        new Thread(new Runnable() {
            @Override
            public void run () {

                try {
                    // 端口号范围0 ~ 65535
                    // 0 ~ 1024 不允许使用，
                    ServerSocket server = new ServerSocket(7890);
                    Socket socket = server.accept();
                    InputStream is = socket.getInputStream();
                    ObjectInputStream ois = new ObjectInputStream(is);
                    Object o = ois.readObject();
                    Person p = (Person) o;
                    Log.d("RemoteService", "p:" + p);
                    socket.close();
                    server.close();

                } catch (IOException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }

    @Override
    public int onStartCommand (Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }
}
